#pragma once
#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <strings.h>
#include <functional>

namespace Server
{
    using namespace std;

    static const string defaultIp = "0.0.0.0";

    static const int gnum = 1024;

    enum
    {
        USAGE_ERR = 1,
        SOCKET_ERR,
        BIND_ERR,
        OPEN_ERR
    };

    typedef function<void(int,string,uint16_t,string)> func_t;

    class udpServer
    {
    public:
        udpServer(const func_t& cb,const uint16_t &port, const string &ip = defaultIp)
        :_callback(cb),_port(port),_ip(ip),_sockfd(-1)
        {
            
        }

        void initServer()
        {
            //1、创建socket套接字 socket函数
            _sockfd = socket(AF_INET,SOCK_DGRAM,0);
            if(_sockfd == -1)
            {
                cerr<<"socket error: "<< errno <<" : "<<strerror(errno)<<endl;
                exit(SOCKET_ERR);
            }
            cout << "socket success: " << " : " << _sockfd << endl;

            //2、绑定端口号port和公网ip  bind函数
            struct sockaddr_in local;//在用户栈上定义了一个变量注意是in
            bzero(&local,sizeof(local));//初始化为0

            local.sin_family = AF_INET;
            local.sin_port = htons(_port);//htons大小端转化
            //local.sin_addr.s_addr = inet_addr(_ip.c_str());

            local.sin_addr.s_addr = INADDR_ANY;//任意地址绑定，这是服务的的真实写法
            int n = bind(_sockfd,(struct sockaddr*)&local,sizeof(local));
            if(n == -1)
            {
                cerr<<"bind error: "<< errno <<" : "<<strerror(errno)<<endl;
                exit(BIND_ERR);
            }
        }

        void start()//启动，
        {
            //服务器的本质其实就是一个死循环，一般叫做常驻内存的进程
            //所以要防止内存泄漏
            char buffer[gnum];
            for(; ;)
            {
                //读取数据
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);//必填
                ssize_t s = recvfrom(_sockfd,buffer,sizeof (buffer) - 1,0,(struct sockaddr*)&peer,&len);
                if(s > 0)
                {
                    buffer[s] = 0;
                    string clientip = inet_ntoa(peer.sin_addr);
                    uint16_t clientport = ntohs(peer.sin_port);
                    string message = buffer;

                    cout<<clientip<<"["<<clientport<<"]#"<<message<<endl;

                    _callback(_sockfd,clientip,clientport,message);
                }
            }
        }

        ~udpServer()
        {

        }

    private:
        uint16_t _port;
        string _ip;
        int _sockfd;
        func_t _callback;//回调
    };
}



